package com.example.myapplication.jetpack.databinding.adapter;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.databinding.DataBindingUtil;

import com.example.myapplication.BR;
import com.example.myapplication.R;
import com.example.myapplication.base.BaseActivity;
import com.example.myapplication.databinding.LayoutDatabindingadapterBinding;

/**
 * Created by ymz0427 on 2022/12/7
 */
public class DataBindingAdapterActivity extends BaseActivity {

    private final ColorWrapper colorWrapper = new ColorWrapper();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutDatabindingadapterBinding binding =
            DataBindingUtil.setContentView(this, R.layout.layout_databindingadapter);

        colorWrapper.setColor(Color.RED);
        binding.setColorWrapper(colorWrapper);

        TextView textView = findViewById(R.id.textView);
        textView.setOnClickListener(v -> {
            Log.d(TextColorAdapter.TAG, "change color");
            // 设置颜色后会一直循环 setTextColor、getColor、setColor
            textView.setTextColor(Color.BLUE);
        });
    }

    public static class ColorWrapper extends BaseObservable {

        private int color;

        @Bindable
        public int getColor() {
            return color;
        }

        public void setColor(int color) {
            Log.d(TextColorAdapter.TAG, "setColor(" + color);
            this.color = color;
            notifyPropertyChanged(BR.color);
        }
    }
}
